<?php

namespace Home\Controller;
use Common\Controller\BaseController;
use Think\Exception;

class UserController extends BaseController {

    static $ROLE_WEIBAO  = 1;
    static $ROLE_MANAGER = 2;
    static $ROLE_SYS_MANAGER = 3;
    static $ROLE_COMPANY = 4;

    public function index(){

        $condition = I('get.condition','','htmlspecialchars');
        $userModel = D('User');
        $where     = !empty($condition)  ? "locate('{$condition}',user.nickname) and del=1": "del=1";
        $where    .= " and user.role_id=".self::$ROLE_WEIBAO;
        $field = "user.*,role.name as rolename";
        $list = $userModel
                ->field($field)
                ->join('role on user.role_id=role.role_id')
                ->where($where)
                ->order('user.reg_time')
                ->select();
        
        $this->assign('list',$list);
        $this->assign('condition',$condition);

       $this->display('index');
    }

    public function add(){

        $roleModel = D('Role');

        $role_list = $roleModel->getRoleList();

        $this->assign('role_list',$role_list);
        $this->assign('now',date('Y-m-d',time()));
        $this->display('add');
    }
    
    public function edit(){

        $user_id    = I('get.uid');
        $userModel  = D('User');

        $user = $userModel->where('user_id='.intval($user_id))->limit(1)->select();

        if(empty($user)){
            $this->error('员工不存在');
        }

        $roleModel = D('Role');
        $role_list = $roleModel->getRoleList();

        $this->assign('role_list',$role_list);
        $this->assign('user',$user[0]);
        $this->display('edit');
    }

    public function save(){

        $ret = array('status'=>200,'msg'=>'','content'=>'');

        if(IS_POST){
            try{

                $userModel = D('User');
                $post      = I('post.');
                $res = $userModel->saveUser($post);
                $ret['status'] = (false==$ret) ? 0 : 200;
                $ret['msg'] = $res['msg'];

            }catch (\Exception $e){

                $ret['status'] = $e->getCode();
                $ret['msg']    = $e->getMessage()." on line ".$e->getLine();
            }
        }else{
            $ret['msg'] = '请求不允许';
        }

        $this->ajaxReturn($ret);
    }
    public function delete(){

        $user_id    = I('get.uid');
        $userModel  = D('User');

        $user = $userModel->where('user_id='.intval($user_id))->limit(1)->select();

        if(!empty($user)){
            try{
                $info = array('user_id'=>intval($user_id),'del'=>2);
                $res = $userModel->setField($info);
                if(false===$res){
                    $ret['status'] = 0;
                    $ret['msg']    = "删除失败";
                }else{
                    $ret['msg']    = "删除成功";
                }

            }catch (\Exception $e){

                $ret['status'] = $e->getCode();
                $ret['msg']    = $e->getMessage()." on line ".$e->getLine();
            }
        }else{
            $ret['msg'] = '用户不存在';
        }
        $this->ajaxReturn($ret);
    }
    public function getSore(){
        $user_id    = I('get.uid');
        $commentModel  = D('Comment');
        exit;
        $user = $commentModel->where('user_id='.intval($user_id))->group("")->select();

        if(!empty($user)){
            try{
                $info = array('user_id'=>intval($user_id),'del'=>2);
                $res = $userModel->setField($info);
                if(false===$res){
                    $ret['status'] = 0;
                    $ret['msg']    = "删除失败";
                }else{
                    $ret['msg']    = "删除成功";
                }

            }catch (\Exception $e){

                $ret['status'] = $e->getCode();
                $ret['msg']    = $e->getMessage()." on line ".$e->getLine();
            }
        }else{
            $ret['msg'] = '用户不存在';
        }
        $this->ajaxReturn($ret);
    }

    public function view(){
        $user_id    = I('get.uid');
        $userModel  = D('User');

        $field = "user.*,role.name as rolename";
        $user = $userModel
            ->field($field)
            ->join('role on user.role_id=role.role_id')
            ->where('user.user_id='.intval($user_id."and del=1"))
            ->limit(1)
            ->select();

        if(empty($user)){
            $this->error('员工不存在');
        }
        
        $this->assign('user',$user[0]);
        $this->display('view');
    }

    public function login(){

        $token     = I('post.token','','htmlspecialchars');
        if(empty($token)&&$token!=self::$token){
           
            $url = I('get.url');
            $url =  !empty($url) ? $url: base64_encode(self::$home_page) ;
            $this->assign('url',$url);
            $this->display('login');

        }else{

            $user_name = I('post.name','','htmlspecialchars');
            $password  = I('post.password','','htmlspecialchars');
            $userModel  = D('User');
            $redirect_url = I('post.url');

            if(!empty($user_name) && !empty($password)){
                try{

                    $res = $userModel->getUserByName($user_name);
                    if(empty($res)){
                        $ret['status'] = 0;
                        $ret['msg']    = "用户名不存在";
                    }else{
                        $password = $userModel->encryptPass($password,$user_name);
                        if($password !=$res['password']){
                            $ret['status'] = 0;
                            $ret['msg']    = "密码错误";
                        }else{
                            
                            $this->getLoginInfo($res);

                            $ret['status'] = 1;
                            $ret['msg']    = "登录成功";
                            $ret['url']    = !empty($redirect_url) ? base64_decode($redirect_url) : self::$home_page;
                        }
                    }

                }catch (\Exception $e){

                    $ret['status'] = $e->getCode();
                    $ret['msg']    = $e->getMessage()." on line ".$e->getLine();
                }
            }else{
                $ret['status'] = 0;
                $ret['msg'] = '用户名和密码不能为空';
            }

            $this->ajaxReturn($ret);
        }
    }

    public function logout(){
        session_destroy();
        $this->success('退出成功',U('Home/User/login'));
    }
    public function getLoginInfo($res){
        
        $roleModel  = D('Role');

        $_SESSION['USER']['INFO'] = $res;
        $_SESSION['USER']['PURVIEW'] =  $roleModel->getPurview($res['role_id']);

        if(self::$ROLE_COMPANY == $res['role_id']){
            //如果是企业法人，获取其公司id存入session，以备后面使用
            $companyModel = D('Company');
            $_SESSION['USER']['COMPANY'] = $companyModel->getCompanyByUserId();
        }
    }
}